import '../public/index'
import url from '../data/url'
import request from '../data/request'
import { header } from '../data/config'

import {
  userName   as valid_userName,
  password   as valid_password,
  contacts   as valid_contacts,
  mobile     as valid_mobile
} from '../data/validate'

const base                = url.base,
      editOperator        = request.editOperator,
      getOperatorRoleArea = request.getOperatorRoleArea,
      getOperatorBuild    = request.getOperatorBuild,
      getOperatorRole     = request.getOperatorRole;

// 页面标题
const title  = '操作员',
      action = '添加';

let form = new Vue({
  el: '#form',
  data: () => {
    return ({
      loginName: '',
      loginPassword: '',
      realName: '',
      phone: '',
      email: '',
      roleIds: 1,
      roleList: '',
      dataRole: 1,
      areaId: '',
      areaList: '',
      buildingIds: [],
      buildingList: '',
      isLock: true
    })
  },
  mounted: function () {

    let that = this;

    that.getRole();
    that.getArea();

    valid();
  },
  methods: {
    // 获取角色列表
    getRole: () => {

      let loading = layer.msg('初始化数据中...', {
        icon: 16,
        time: 0
      });

      $.ajax({
        url: base + getOperatorRole,
        headers: header
      })
        .done(function (res) {
          if (res.code === 0) {
            console.log('初始化角色列表成功');

            form.roleList = res.object;
          } else {
            console.log(res.error || '初始化角色数据失败')

          }
        })
        .fail(function (res) {
          console.log(res.error || '初始化角色数据失败')

        })
        .always(function (res) {
          layer.close(loading);

        })
    },
    // 获取区域列表
    getArea: () => {

      let loading = layer.msg('初始化数据中...', {
        icon: 16,
        time: 0
      });

      $.ajax({
        url: base + getOperatorRoleArea,
        headers: header
      })
        .done(function (res) {
          if (res.code === 0) {
            console.log('初始化区域列表成功');
            form.isLock   = false;
            form.areaList = res.object;
          } else {
            console.log(res.error || '初始化区域数据失败');

            layer.msg('该账号无权限新建操作员，跳转至列表页', {
              icon: 5,
              time: 0
            });

            setTimeout(() => {

              window.location.href = './index.html';
            }, 2000)
          }
        })
        .fail(function (res) {
          console.log(res.error || '初始化区域数据失败')

        })
        .always(function (res) {
          layer.close(loading)
        })
    },
    // 获取楼盘列表
    getBuild: (city) => {
      let loading = layer.msg('初始化数据中...', {
        icon: 16,
        time: 0
      });

      $.ajax({
        url: base + getOperatorBuild,
        headers: header,
        data: {
          areaId: city,
          enterId: ''
        }
      })
        .done(function (res) {
          console.log('获取楼盘成功')
          console.log(res)

          form.buildingList = res.buildings;

        })
        .fail(function (res) {
          let error = res.error;
          layer.msg(error || '获取楼盘失败', {
            icon: 5
          })
        })
        .always(function () {
          layer.close(loading)
        })
    }
  }
})

function valid () {

  let form_valid,
      $form = $('#form')

  $.validator.setDefaults({ // 只能放在validate规则配置之前

    // 提交事件
    submitHandler: () => {
      console.log('submit!')

      let loading_modal = layer.msg('提交中...', {
        icon: 16,
        time: 0
      })

      form.isLock = true;

      let roleArr = new Array;
      roleArr.push(form.roleIds);

      $.ajax({
        url: base + editOperator,
        type: 'POST',
        headers: header,
        contentType: 'application/json',
        data: JSON.stringify({
          loginName: form.loginName ? form.loginName : '',
          loginPassword: form.loginPassword ? form.loginPassword : '',
          realName: form.realName ? form.realName : '',
          phone: form.phone ? form.phone : '',
          email: form.email ? form.email : '',
          roleIds: form.roleIds ? roleArr : '',
          roleName: form.roleIds ? $(`input[name=roleIds][value=${form.roleIds}]`).text() : '',
          dataRole: form.dataRole ? form.dataRole : '',
          areaId: form.areaId ? form.areaId : '',
          buildingIds: form.buildingIds ? form.buildingIds.join(',') : '',
          id: '',
        })
      })
        .done(function (res) {
          console.log(res)

          if (res.code === -1) {
            layer.msg(res.message, {
              icon: 5
            })

            return
          }

          layer.msg(`${action}${ title }成功`, {
            icon: 6
          })

          // 重置表单
          $.extend(form.$data, form.$options.data())

          setTimeout(() => {
            window.location = './index.html'
          }, 1000)
        })
        .fail(function (res) {
          console.log(res)

          layer.msg(`添加${ title }失败`, {
            icon: 5
          })

          console.log("error");
        })
        .always(function (res) {

          layer.close(loading_modal)
          form.isLock = false

        })

    }
  })

  // 验证
  form_valid = $form.validate({
    errorPlacement: function (error, element) {
      error.appendTo(element.parents('.col-xs-24'))
    },
    rules: {
      roleIds: {
        required: true
      },
      email: {
        email: true
      },
      realName: valid_contacts,
      loginName: valid_userName,
      loginPassword: valid_password,
      phone: valid_mobile,
    }
  })

}